package com.gqb.load;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.gqb.annotation.Action;
import com.gqb.annotation.Controller;
import com.gqb.spring.tag.Scan;
import com.gqb.util.ClassUtil;
import com.gqb.web.Handler;
import com.gqb.web.Request;

public class ControllerLoad {
	private static Map<Class<?>, Object> controllersMap=new HashMap<Class<?>, Object>();
	private static Map<Request, Handler> requestHandlerMap=new HashMap<>();
	
	public static void load(List<Scan> scans) throws UnsupportedEncodingException, ClassNotFoundException, InstantiationException, IllegalAccessException{
		Set<Class<?>> classes=new HashSet<>();
		for (Scan scan : scans) {
			String packageName=scan.getPackageName();
			classes.addAll(ClassUtil.getClasses(packageName, Controller.class));
		}
		for (Class<?> class1 : classes) {
			Object object=class1.newInstance();
//			List<Field> fieldsAnnotation=ClassUtil.getFields(class1, Inject.class);
			controllersMap.put(class1, object);
			List<Method> methodsAnnotation=ClassUtil.getMethods(class1, Action.class);
			for (Method method : methodsAnnotation) {
				Action action=method.getAnnotation(Action.class);
				String pathMethod=action.value();
				String[] params=pathMethod.split(":");
				Request request=new Request(params[0], params[1]);
				Handler handler=new Handler(class1, method);
				requestHandlerMap.put(request, handler);
			}
		}
	}
	
	
	/**
	 * 获取对应请求的Handler
	 * @param requestMethod
	 * @param requestPath
	 * @return
	 */
	public static Handler getHandler(String requestMethod,String requestPath){
		Request request=new Request(requestMethod.toLowerCase(), requestPath);
		return requestHandlerMap.get(request);
	}
	
	/**
	 * 获取对应的控制器的实例controller
	 * @param controllerClass 控制器的class类型
	 * @return
	 */
	public static Object getController(Class<?> controllerClass){
		return controllersMap.get(controllerClass);
	}
	
	
}
